﻿using System;
using System.Web.UI;
using System.IO;
using Business;
using System.Data;
using EAGetMail;
using OpenPop.Mime;
using OpenPop.Pop3;

public class Oil_Report : Page
{
	private string m_curpath = "";
	private string sampleID;
	private string status;
	
	protected void Page_Load(object sender, EventArgs e)
	{
		string tempFolder = String.Format("{0}\\", Server.MapPath(""));
		m_curpath = tempFolder;
		RetrieveEmails();
		ListMail();
	}
	
	public void proceed_oil()
	{
		string tempFolder = String.Format("{0}\\", Server.MapPath(""));
		m_curpath = tempFolder;
		RetrieveEmails();
		ListMail();
	}
	
	protected void RetrieveEmails()
	{
		// Create a new instance of the Pop3Client class.
		var client = new Pop3Client();
		try
		{
			string mailsPath = AppDomain.CurrentDomain.BaseDirectory + "Mails\\";
			// Create Mails folder to store downloaded messages if it does not exist.
			if (!Directory.Exists(mailsPath))
				Directory.CreateDirectory(mailsPath);
			// Connect to the server.
            int port = int.Parse("110");
            string hotName = "mail.i2iportal.com.au";
            client.Connect(hotName, port, false);
            string userName = "oil@i2iportal.com.au";
            string password = "93email827account";
            client.Authenticate(userName, password, AuthenticationMethod.Auto);
            var list = OilReport.OilReportHelper.FetchAllMessages(hotName, port, false, userName, password);
            int messages = int.Parse("100");
			if (list.Count < messages)
				messages = list.Count;

            for (int i = 0; i < messages; i++)
            {
                Message message = list[i];
                string filename = mailsPath + message.Headers.MessageId + ".eml";
                var file = new FileInfo(filename);
                if (!File.Exists(filename))
                {
                    message.Save(file);
                }
            }
		}
		catch (Exception exc)
		{
			string str = string.Format(null, "Exception: {0}", exc.Message);
			Response.Write(str);
		}
		finally
		{
			// Disconnect.
			client.Disconnect();
		}
	}

	private void ListMail()
	{
		string tempFolder = String.Format("{0}\\Mails", Server.MapPath(""));
		m_curpath = tempFolder;
		string mailFolder = String.Format("{0}", m_curpath);
		if (!Directory.Exists(mailFolder))
			Directory.CreateDirectory(mailFolder);


		string[] files = Directory.GetFiles(mailFolder, "*.eml");
		int count = files.Length;
		for (int i = 0; i < count; i++)
		{
			string fullname = files[i];
			Mail oMail = new Mail("TryIt");
			oMail.Load(fullname, true);
			string subject = Server.HtmlEncode(oMail.Subject).Replace(" ", "");
			string[] sArray = subject.Split(new char[2] { '[', ']' });
			string[] samplearray = new string[11];
			int m = 0;
			foreach (string str in sArray)
			{
				string getparts = str.ToString();
				if (getparts != "FW:" && getparts != "" && getparts != "ALERT" && getparts != " ")
				{
					samplearray[m] = getparts;
					m++;
				}

			}
			oMail.Load(fullname, true);
			string uin = getUIN(fullname);
			string sampleddate = getSampledate(fullname);

			if (uin != "")
			{
				samplearray[7] = uin;//0:  "ID:19843657-43316" 1:"BBSMillme" 2:"MM0EAF10AF" 3:"GearboxCh" 4: "733031100" 5:"Abnormal" 6:"(TrialVersion)" 7:"MM0EAF10AF001MG2"
			}
			string attachmentlink = getAttachmentLink(fullname);
			if (attachmentlink != "")
			{
				samplearray[8] = attachmentlink;
			}

			if (sampleddate != "")
				samplearray[9] = sampleddate;
			samplearray[10] = oMail.ReceivedDate.ToString();
			MatchSample(samplearray);
			oMail.Clear();
		}
	}

	private void MatchSample(string[] sampleInfo)
	{
		sampleID = sampleInfo[4];
		string uinNO = sampleInfo[7];
		status = sampleInfo[5];
		string attachmentlink = sampleInfo[8];
		string sampledate = sampleInfo[9];
		string select_query2 = "SELECT o.receive_date, o.Component_id,o.id, c.Value FROM OilReports o join ComponentTechnicalData c on"
			+ " o.Component_id=c.Component_id WHERE (o.tested_date"
			+ "=convert(datetime,'" + sampledate + "',103)) and (c.Value='" + uinNO + "' or c.Value='" + sampleID + "') and (c.Attribute='uin' OR c.Attribute='UIN')";

		CreateConn objcon = new CreateConn();
		DataTable dt = objcon.SQLConnDataTable(select_query2);
		if (dt != null && dt.Rows.Count > 0)
		{
			try
			{
				if (dt != null && dt.Rows.Count > 0)
				{
					foreach (DataRow dr in dt.Rows)
					{

						if (dr["receive_date"] != null && dr["receive_date"].ToString() != "")
						{
							DateTime saved_date = Convert.ToDateTime(dr["receive_date"]);
							DateTime current_date = Convert.ToDateTime(sampleInfo[10]);
							if (current_date > saved_date)
							{
								string id = dr["id"].ToString();
								string uinOrsf = dr["Value"].ToString();
								double Num;

								bool isnum = double.TryParse(uinOrsf.Trim(), out Num);
								if (isnum)
								{
									//sample id is saved in technical data, replace with uin;
									string update_UIN = "Update ComponentTechnicalData set Value='" + uinNO + "' WHERE (Attribute='UIN' or Attribute='uin') and Component_id IN (SELECT Component_id FROM OilReports WHERE id='" + id + "')";
									CreateConn objcon2 = new CreateConn();
									objcon2.SQLConnDataTable(update_UIN);
								}
								//update sampleid in oilreports table
								String modify_query = "Update OilReports set sample_id='" + sampleID + "', receive_date=CONVERT(varchar(10),'" + sampleInfo[10] + "',103), reportlink='" + attachmentlink + "',status='" + status + "' WHERE id='" + id + "'";
								CreateConn objcon_modify = new CreateConn();
								objcon_modify.SQLConnDataTable(modify_query);
							}
						}
						else
						{

							string id = dr["id"].ToString();
							string uinOrsf = dr["Value"].ToString();
							double Num;
							bool isnum = double.TryParse(uinOrsf.Trim(), out Num);
							if (isnum)
							{
								//sample id is saved in technical data, replace with uin;
								string update_UIN = "Update ComponentTechnicalData set Value='" + uinNO + "' WHERE (Attribute='UIN' or Attribute='uin') and Component_id IN (SELECT Component_id FROM OilReports WHERE id='" + id + "')";
								CreateConn objcon2 = new CreateConn();
								objcon2.SQLConnDataTable(update_UIN);
							}
							//update sampleid in oilreports table


							String modify_query = "Update OilReports set sample_id='" + sampleID + "',receive_date=CONVERT(varchar(10),'" + sampleInfo[10] + "',103), reportlink='" + attachmentlink + "',status='" + status + "' WHERE id='" + id + "'";
							CreateConn objcon_modify = new CreateConn();
							objcon_modify.SQLConnDataTable(modify_query);
						}
					}
				}
			}
			catch (Exception e)
			{
				String Errmsg = e.ToString();
			}

		}
	}
	
	private string getAttachmentLink(string emlFile)
	{
		Mail oMail = new Mail("TryIt");
		oMail.Load(emlFile, false);

		string attname = "";
		EAGetMail.Attachment[] atts = oMail.Attachments;
		int count = atts.Length;
		if (count > 0)
		{
			for (int i = 0; i < count; i++)
			{
				EAGetMail.Attachment att = atts[i];

				if (att.Name.IndexOf("pdf") != -1)
				{
					if (att.Name.IndexOf("pdf") != -1)
					{
						string name = att.Name;
						string tempFolder = String.Format("{0}\\Mails", Server.MapPath(""));
						att.SaveAs(tempFolder + "/" + att.Name, true);
						return name;
					}

				}

			}
		}
		return attname;
	}

	private string getUIN(string emlFile)
	{
		Mail oMail = new Mail("TryIt");
		oMail.Load(emlFile, false);

		string html = oMail.HtmlBody;
		string uin = "";
		int startindex = html.IndexOf("Compartment UIN:");
		try
		{
			string uin_pre = html.Substring(startindex + 16, 30);

			string uin_2 = uin_pre.Replace(" ", "");

			int endindex2 = uin_2.IndexOf('\r');
			int endindex = 0;
			int endindex_n = uin_2.IndexOf('\n');
			int endindex_bracket = uin_2.IndexOf('<');
			if (endindex2 != -1)
			{
				endindex = endindex2;
			}
			else if (endindex_n != -1)
			{
				if (endindex_bracket != -1 && endindex_n > endindex_bracket)
				{
					endindex = endindex_bracket;
				}
				else if (endindex_bracket != -1)
				{
					endindex = endindex_n;
				}
			}
			string uin_result = uin_2.Substring(0, endindex);
			uin = uin_result;
		}
		catch (Exception e)
		{
			String ErrMsg = e.ToString();
		}
		return uin;
	}

	private string getSampledate(string emlFile)
	{
		Mail oMail = new Mail("TryIt");
		oMail.Load(emlFile, false);

		string html = oMail.HtmlBody;
		string uin = "";
		int startindex = html.IndexOf("Date sampled:");
		int endindex = html.IndexOf("Severity");
		try
		{
			string uin_pre = html.Substring(startindex, endindex - startindex);
			string uin_2;
			uin_2 = uin_pre.Replace(" ", ""); 
			int endindex2 = uin_2.IndexOf('\r');
			int endindex_n = uin_2.IndexOf('\n');
			int endindex_bracket = uin_2.IndexOf('<');
			if (endindex2 != -1)
			{
				//  endindex2 = endindex2;
			}
			else if (endindex_n != -1)
			{
				if (endindex_bracket != -1 && endindex_n > endindex_bracket)
				{
					endindex2 = endindex_bracket;
				}
				else if (endindex_bracket != -1)
				{
					endindex2 = endindex_n;
				}
			}
			else if (endindex_bracket != -1)
			{
				endindex2 = endindex_bracket;
			}
			uin = uin_2.Substring(12, endindex2 - 12);
		}
		catch (Exception e)
		{
			String ErrMsg = e.ToString();
		}
		return uin;
	}
}
